package lib.bone.access.module.post;

import cn.hutool.core.lang.Validator;
import lib.bone.access.module.post.domain.NepuPost;
import lib.bone.access.module.userpost.NepuUserPostDAO;
import lib.bone.common.constant.ResponseCodeConst;
import lib.bone.common.core.domain.PageResultDTO;
import lib.bone.common.core.domain.ResponseDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class NepuPostServiceImpl implements NepuPostService {
    @Autowired
    NepuPostDAO nepuPostDAO;

    @Autowired
    NepuUserPostDAO nepuUserPostDAO;

    @Override
    public List<NepuPost> getAll() {
        return nepuPostDAO.findAll();
    }

    @Override
    public Optional<NepuPost> findByName(String name) {
        return nepuPostDAO.findByPostType(name);
    }

    @Override
    public NepuPost updateOne(NepuPost post) {
        return null;
    }

    @Override
    public Boolean isSame(NepuPost post) {
        return nepuPostDAO.existsByPostTypeAndPostLevelAndPostGrade(post.getPostType(),post.getPostLevel(),post.getPostGrade());
    }

    @Override
    public PageResultDTO<NepuPost> getAll(Pageable pageable, Example<NepuPost> example) {
        Page<NepuPost> page;
        //是否为空 --
        if(Validator.isEmpty(example)){
            page = nepuPostDAO.findAll(pageable);
        }else {
            page = nepuPostDAO.findAll(example,pageable);
        }
        List<NepuPost> list = page.getContent();
        PageResultDTO<NepuPost> pageResultDTO = new PageResultDTO<>();
        pageResultDTO.setContent(list);
        pageResultDTO.setSize(page.getSize());
        pageResultDTO.setTotalPages(page.getTotalPages());
        pageResultDTO.setNumber(page.getNumber());
        pageResultDTO.setTotalElements(page.getTotalElements());

        return pageResultDTO;
    }

    @Override
    public ResponseDTO deleteById(String id) {
        // 查询是否存在
        Boolean exist = nepuUserPostDAO.existsByPostId(id);
        if (exist){
            return ResponseDTO.wrap(ResponseCodeConst.FORBIDDEN,"请取消与该岗位绑定用户信息");
        }
        nepuPostDAO.deleteById(id);
        return ResponseDTO.succMsg("删除成功");
    }
    @Override
    public Optional<NepuPost> getById(String id) {
        return nepuPostDAO.findById(id);
    }

    @Override
    public NepuPost saveOne(NepuPost post) {
        return nepuPostDAO.save(post);
    }

}
